package com.yunao.service.report.info.factory;



import com.yunao.service.report.Convert;
import com.yunao.service.report.Profile;
import com.yunao.service.report.info.MailService;
import org.json.JSONArray;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.*;
import java.util.Map;
import java.util.Properties;
import java.util.Random;

/**
 * javaMail邮件发送
 * 
 * @author guild
 * 
 */
public class JavaMail implements MailService {

	private String host;
	private String user;
	private String pswd;
	private String guanzhu;


	protected JavaMail() {
		try {
			Profile profile = new Profile(Profile.ESOU_CONF);
			host = profile.getValue("mail.host", "localhost:8080");
			user = profile.getValue("mail.user", "cnxunao_report@xunao.com");
			pswd = profile.getValue("mail.pswd", "report-2012");
			guanzhu = profile.getValue("mail.guanzhu", "社会稳定");
			System.out.println("user:"+user);
		} catch (Exception e) {
			e.printStackTrace();

		}
	}
	
	/**
	 * 发送邮件
	 * 
	 * @param subject
	 *            主题
	 * @param toEmails
	 *            目的邮箱
	 * @param content
	 *            邮件内容
	 */
	public void sendMail(String subject, String[] toEmails, String content) throws Exception {
		// 正文
		MimeBodyPart bodyPart = createBody(content);
		// 所有
		MimeMultipart allPart = new MimeMultipart("mixed");
		allPart.addBodyPart( bodyPart);
		Session session = createSession();
		MimeMessage mimeMessage = createMessage(session, subject, user, toEmails, allPart);
		mimeMessage.setFrom(new InternetAddress("cnxunao@yunaodata.com"));
		Transport transport = session.getTransport();
		transport.connect(host,user,pswd);
		transport.sendMessage(mimeMessage, mimeMessage.getRecipients(Message.RecipientType.TO));
		transport.close();
	}

	/**
	 * 发送邮件
	 * 
	 * @param subject
	 *            主题
	 * @param toEmail
	 *            目的邮箱
	 * @param content
	 *            邮件内容
	 * @param attachment
	 *            附件
	 */
	public void sendMail(String subject, String toEmail, String content, String... attachment) throws Exception {
		String[] toEmails = null;
		if (toEmail.indexOf(",") != -1)
			toEmails = Convert.split(toEmail, ",");
		else
			toEmails = new String[] { toEmail };
		sendMail(subject, toEmails, content, attachment);
	}

	/**
	 * 发送邮件
	 * 
	 * @param subject
	 *            主题
	 * @param toEmails
	 *            目的邮箱
	 * @param content
	 *            邮件内容
	 * @param attachment
	 *            附件
	 */
	public void sendMail(String subject, JSONArray toEmails, String content, String... attachment) throws Exception {
		String[] addrs = new String[toEmails.length()];
		for (int i = 0; i < toEmails.length(); i++) {
			addrs[i] = toEmails.getString(i);
		}
		sendMail(subject, addrs, content, attachment);
	}

	/**
	 * 发送邮件
	 * 
	 * @param subject
	 *            主题
	 * @param toEmails
	 *            目的邮箱
	 * @param content
	 *            邮件内容
	 * @param attachment
	 *            附件
	 */
	public void sendMail(String subject, String[] toEmails, String content, String... attachment) throws Exception {
		if(subject.equals(guanzhu))
			user="cnxunao_report11@esou.me";
		// 正文
		MimeBodyPart bodyPart = createBody(content);
		MimeBodyPart attachmentPart = createAttachment(attachment);
		// 所有
		MimeMultipart allPart = new MimeMultipart("mixed");
		if (attachmentPart != null)
			allPart.addBodyPart(attachmentPart);
		allPart.addBodyPart(bodyPart);
		Session session = createSession();
		MimeMessage mimeMessage = createMessage(session, subject, user, toEmails, allPart);
		mimeMessage.setFrom(new InternetAddress("cnxunao@pFus6MqfEglMuvfPNtUYybesajwMFVuV.sendcloud.org"));
		Transport transport = session.getTransport();
	
		transport.connect(host,user,pswd);
		transport.sendMessage(mimeMessage, mimeMessage.getRecipients(Message.RecipientType.TO));
		transport.close();
	}

	/**
	 * 发送邮件
	 * 
	 * @param subject
	 *            主题
	 * @param toEmails
	 *            目的邮箱
	 * @param content
	 *            邮件内容
	 * @param attachment
	 *            附件
	 * @throws Exception
	 */
	public void sendMail(String subject, String[] toEmails, String content, Map<String, String> attachment) throws Exception {
		// 正文
		MimeBodyPart bodyPart = createBody(content);
		MimeBodyPart attachmentPart = createAttachment(attachment);
		// 所有
		MimeMultipart allPart = new MimeMultipart("mixed");
		if (attachmentPart != null)
			allPart.addBodyPart(attachmentPart);
		allPart.addBodyPart(bodyPart);
		Session session = createSession();
		MimeMessage mimeMessage = createMessage(session, subject, user, toEmails, allPart);
		mimeMessage.setFrom(new InternetAddress("cnxunao@yunaodata.com"));
		Transport transport = session.getTransport();
		System.out.println(host+user+pswd);
		transport.connect(host,user,pswd);
		transport.sendMessage(mimeMessage, mimeMessage.getRecipients(Message.RecipientType.TO));
		transport.close();
	}

	/**
	 * 创建 Session 配置传输的协议 是否身份认证
	 */
	private Session createSession() {
		Properties p = new Properties();
		p.setProperty("mail.transport.protocol", "smtp");
		p.setProperty("mail.smtp.auth", "true");
		Session session = Session.getInstance(p);
		session.setDebug(false);
		return session;
	}

	/**
	 * 创建附件
	 */
	private MimeBodyPart createAttachment(String... filenames) throws Exception {
		if (filenames == null || filenames.length == 0)
			return null;
		MimeBodyPart attachmentPart = new MimeBodyPart();
		for (String filename : filenames) {
			FileDataSource fds = new FileDataSource(filename);
			if (!fds.getFile().exists())
				continue;
			attachmentPart.setDataHandler(new DataHandler(fds));
			attachmentPart.setFileName(filename);
		}
		return attachmentPart;
	}

	/**
	 * 创建附件
	 */
	private MimeBodyPart createAttachment(Map<String, String> attachment) throws Exception {
		if (attachment == null || attachment.size() == 0)
			return null;
		MimeBodyPart attachmentPart = new MimeBodyPart();
		for (Map.Entry<String, String> entry : attachment.entrySet()) {
			String filename = entry.getKey();
			String filepath = entry.getValue();
			FileDataSource fds = new FileDataSource(filepath);
			if (!fds.getFile().exists())
				continue;
			attachmentPart.setDataHandler(new DataHandler(fds));
			attachmentPart.setFileName(MimeUtility.encodeText(filename));
		}
		return attachmentPart;
	}

	/**
	 * 创建正文
	 */
	private MimeBodyPart createBody(String content) throws Exception {
		MimeBodyPart bodyPart = new MimeBodyPart();
		// 用于组合文件和图片, "related" 型 MimeMultipart 对象
		MimeMultipart multiPart = new MimeMultipart("related");
		// 正文部分
		MimeBodyPart textPart = new MimeBodyPart();
		textPart.setContent(content, "text/html;charset=utf8");
		multiPart.addBodyPart(textPart);
		bodyPart.setContent(multiPart);
		return bodyPart;
	}

	/**
	 * Message
	 * 
	 * @param subject
	 *            主题
	 * @param from
	 *            发件人
	 * @param addrs
	 *            收件人
	 * @param allPart
	 *            正文附件
	 */
	private MimeMessage createMessage(Session session, String subject, String from, String[] addrs,
									  MimeMultipart allPart) throws Exception {
		MimeMessage mimeMessage = new MimeMessage(session);
		// 主题
		mimeMessage.setSubject(subject);
		// 发件人
		mimeMessage.setFrom(new InternetAddress(from));
		// 收件人
		if (addrs != null) {
			Address[] addresses = new InternetAddress[addrs.length];
			for (int i = 0; i < addrs.length; i++) {
				addresses[i] = new InternetAddress(addrs[i]);
			}
			mimeMessage.setRecipients(Message.RecipientType.TO, addresses);
		}
		mimeMessage.setContent(allPart, "text/html");
		mimeMessage.saveChanges();
		return mimeMessage;
	}

	public static void main(String[] args) throws Exception {
		MailService service = InfoFactory.getMail();
		service.sendMail("北京", "guild@cnxunao.com", "北京" + new Random().nextDouble());
	}
}
